package com.beone.admin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.base.SuperServiceImpl;
import com.beone.admin.entity.BasePermission;
import com.beone.admin.mapper.BasePermissionMapper;
import com.beone.admin.service.BasePermissionService;

import com.beone.admin.utils.PaginationGatagridTable;
import com.beone.admin.utils.ServiceUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @Title 运维数据_系统菜单功能权限表 服务实现类
 * @Author 覃球球
 * @Version 1.0 on 2018-01-25
 * @Copyright 长笛龙吟
 */
@Service("BasePermissionService")
public class BasePermissionServiceImpl extends SuperServiceImpl<BasePermissionMapper, BasePermission>
        implements BasePermissionService {
    /**
     * 根据用户ID 获取权限菜单信息
     *
     * @param userId
     * @param actionType page  表示只显示页面权限   all  显示所有权限
     * @return
     */
    public List<BasePermission> getPermissionsesByUserId(String actionType, Integer userId) {
        return baseMapper.getPermissionsesByUserId(actionType, userId);
    }

    /**
     * 根据角色Id 获取权限菜单信息
     *
     * @param roleId
     * @return
     */
    public List<BasePermission> getPermissionsesByRoleId(Integer roleId) {
        List<BasePermission> permisions = baseMapper.getPermissionsesByRoleId(roleId);
        return permisions;
    }

    /**
     * 获取所有权限菜单信息
     *
     * @param nodeType page  表示只显示页面权限   否则   显示所有可用状态下的权限
     * @return
     */
    public List<BasePermission> getAllPermissionses(String nodeType) {
        EntityWrapper<BasePermission> ew = new EntityWrapper<BasePermission>();
        ew.eq("is_index", 1); //仅显示可见菜单

        if ("page".equalsIgnoreCase(nodeType)) {
            ew.eq("node_type", "03"); //03 表示页面权限
        }
        return baseMapper.selectList(ew);
    }


    /**
     * 显示所有可见的菜单权限
     *
     * @param nodeType page 页面权限  all 所有权限
     * @return 所有菜单权限
     */
    public Collection<BasePermission> showPermissionMenuTree(String nodeType, String used) {
        EntityWrapper<BasePermission> ew = new EntityWrapper<BasePermission>();
        if ("used".equals(used)) {
            ew.eq("is_index", 1); //仅显示可见菜单
        }

        if ("page".equalsIgnoreCase(nodeType)) {
            ew.eq("node_type", "03"); // 03 表示权限类型为页面
        }
        List<BasePermission> permissionses = baseMapper.selectList(ew);
        return getPermissionsTree(permissionses, true);
    }

    /**
     * 构建资源权限树结构
     *
     * @param permissionses
     * @param isExpand      true  展开  false  不展开
     * @return
     */
    public Collection<BasePermission> getPermissionsTree(List<BasePermission> permissionses, boolean isExpand) {
        Map<Integer, BasePermission> recordMap = new LinkedHashMap<Integer, BasePermission>();
        for (int i = 0; i < permissionses.size(); i++) {
            BasePermission permission = permissionses.get(i);
            recordMap.put(permission.getNodeId(), permission);
        }

        //构造树结果
        Map<Integer, BasePermission> treeMap = new LinkedHashMap<Integer, BasePermission>();
        for (int i = 0; i < permissionses.size(); i++) {
            BasePermission ct = permissionses.get(i);
            ct.setUrl(ct.getNodeUrl());
            ct.setText(ct.getNameNode());
            ct.setId(ct.getNodeId());
            ct.setParentId(ct.getPid());
            //根据parentId， 判断当前 ct 对象是否有父节点
            BasePermission parent = recordMap.get(ct.getParentId());
            if (parent == null) {
                ct.setState(isExpand ? "open" : "closed");  //关闭目录
                treeMap.put(ct.getId(), ct);
            } else {
                //获取父节点的子节点集合，并把 ct 作为子节点被加入
                List<BasePermission> children = parent.getChildren();
                if (children == null) {
                    children = new ArrayList<BasePermission>();
                    parent.setChildren(children);
                }
                ct.setState("open"); //展开目录
                children.add(ct);
            }
        }
        return treeMap.values();
    }

    /**
     * 分页显示后台权限列表
     *
     * @param id       权限ID
     * @param nodeName
     * @param currPage 当前页码
     * @param pageSize 每页显示记录数
     * @return
     */
    public PaginationGatagridTable getPermissionPagination(String id, String nodeName
            , int currPage, int pageSize) {

        Integer pid = 0;
        if (StringUtils.isNotBlank(id)) {
            pid = Integer.valueOf(id);
        }
        EntityWrapper<BasePermission> ew = new EntityWrapper<BasePermission>();
        ew.eq("a.pid", pid);
        if (StringUtils.isNotBlank(nodeName)) {
            ew.like("a.node_name", nodeName);
        }
        Page<BasePermission> page = new Page<BasePermission>(currPage, pageSize);
        List<BasePermission> rows = baseMapper.getPermissionPagination(page, ew);
        return ServiceUtils.createGatagridTableJson(page, rows);
    }

    /**
     * 保存权限信息
     *
     * @param access
     * @return
     */
    @CachePut("operationMenus")
    public boolean savePermissions(BasePermission access) {
        if (access.getNodeId() == null) {
            //新增
            //access.setIsIndex(1); //可见
            return super.insert(access);
        } else {
            //编辑
            return super.updateById(access);
        }
    }

    /**
     * 获取菜单面包屑
     *
     * @return
     */
    @Cacheable("operationMenus")
    public Map<String, String> getPermissionsBreads() {
        Map<String, String> result = new HashMap<String, String>();
        List<BasePermission> operationAccessList = getPermissionsChildren(getAllPermissionses("all"), 0, null);
        for (BasePermission access : operationAccessList) {
            if (StringUtils.isNoneBlank(access.getNodeUrl())) {
                result.put(access.getNodeUrl(), access.getNameNode());
            }
        }
        return result;
    }

    private static List<BasePermission> getPermissionsChildren(List<BasePermission> accessList, Integer pid, String name) {
        List<BasePermission> operationAccessList = new ArrayList<BasePermission>();
        for (BasePermission access : accessList) {
            if (access.getPid().equals(pid)) {
                if (name != null) {
                    access.setNameNode(name + "-" + access.getNameNode());
                }
                operationAccessList.add(access);
                if (hasChild(accessList, pid)) {
                    List<BasePermission> child = getPermissionsChildren(accessList, access.getNodeId(), access.getNameNode());
                    operationAccessList.addAll(child);
                }
            }
        }
        return operationAccessList;
    }

    private static boolean hasChild(List<BasePermission> accessList, Integer pid) {
        for (BasePermission access : accessList) {
            if (access.getPid().equals(pid)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据nodeId 获取权限信息
     * @param nodeId
     * @return
     */
    public BasePermission getPermissionByNodeId(Integer nodeId){
        return baseMapper.getPermissionByNodeId(nodeId);
    }
}
